<div  class="goods-spec">
	 <div class="speci" >
	   <{foreach from=$goods.spec key=key item=goodsFlatSpecDesc}>
		<{if $goodsFlatSpecDesc.spec_show_type != 'flat'}><{assign var=hasSelSpec value='true'}><{continue}><{/if}>
		<div class='spec-item specItem'>
		<label><span><em><{$goodsFlatSpecDesc.spec_name}></em>：</span></label>
		<div class="rightdiv">
		<ul>
			  <{foreach from=$goodsFlatSpecDesc.option key=skey item="subDesc"}>
			  <{if $goods.used_spec.$skey}>
			  <{if $goodsFlatSpecDesc.display!="block"}>
			  <li> <a href="<{link app=b2c ctl=site_product act=index arg0=$goods.goods_id arg1=$subDesc.spec_goods_images}>" specvid="<{$skey}>" specid="<{$key}>" > <{if $goodsFlatSpecDesc.spec_type=='text'}> <span><nobr><{$subDesc.spec_value}></nobr></span> <{else}> <img src="<{if $subDesc.spec_image}><{$subDesc.spec_image|storager}><{else}><{$spec_default_pic|storager}><{/if}>"  alt="<{$subDesc.spec_value}>" title="<{$subDesc.spec_value}>" width="<{$specimagewidth}>" height="<{$specimageheight}>"> <{/if}> <i title='<{t}>点击取消选择<{/t}>'>&nbsp;</i> </a> </li>
			  <{/if}>
			  <{/if}>
			  <{/foreach}>
			</ul></div>
		</div>
		<{/foreach}>
	  </div>
</div>
<script>

(function(){
 var specExtend={
	sortKeys:function(specHS){
		var sortItem=Object.keys(specHS).sort(),sortHS=$H();
		sortItem.each(function(item){
			sortHS.set(item,specHS[item]);
		});
		return sortHS;
	},
	filterSpec:function(regExp,state){
		var filterArr=[],specSelected=this.selectedHS.getValues();
			this.pid=null;

		this.PRODUCT_HASH.each(function(v,key){
		   var spec=$H(v.spec_private_value_id).getValues(),
			   reg=":"+spec.join(':')+":";
		   if(regExp.test(reg))filterArr.include(spec);
		   if(specSelected.length==this.specNum&&specSelected.every(function(it){
				return	spec.contains(it);	
			},this)){this.pid=key;}
		},this);

		if(state)return this.merge(filterArr);
		return filterArr;
	},
	merge:function(arr){   
		var spec_arr=[];            
		arr[0].each(function(e,i){
			var sarr=[];
			arr.each(function(el){sarr.include(el[i]);});
			spec_arr.push(sarr);
		});             
		return spec_arr;
	},
	collect:function(prearr,arr,hs,key,state){
		var inarr=[],hskeys=hs.getKeys();
		prearr.each(function(el,index){
			var barr=[];
			if(key!=index&&hskeys.contains(index.toString())&&hskeys.length!=prearr.length&&!state){                
				barr.combine(prearr[index].include(arr[index]));
			}else{              
				barr.combine(arr[index].filter(function(item){
					return el.contains(item);
				})); 
			}
			inarr.include(barr);
		});
	   inarr[key]=prearr[key];
	   return inarr;
	},
	to_find:function(selectedHS,specvid){
		var hsvalue=selectedHS.getValues(),hskey=selectedHS.getKeys(), 
			subReg=":"+hsvalue.join(":(\\d+:)*")+":",    
			tpReg = new RegExp(""+subReg.split("(:\\d+:)*")+""),
			keys=selectedHS.keyOf(specvid),sbCollect,        
			filterArr=[],chs=$H(selectedHS);
	
		if(hskey.length>2){
			var sbReg="";                   
			chs.erase(keys).each(function(item,key){
				var tmphs=$H(chs).erase(key).set(keys,specvid),
					v=this.sortKeys(tmphs).getValues();
				sbReg+=":"+v.join(":(\\d+:)*")+":|";            
			},this);                 
			sbReg=new RegExp(""+sbReg.substr(0,sbReg.length-1)+"");     
			if(chs) var preStore=arguments.callee.call(this,chs,chs.getValues()[0]);                      
			var sbSpec=this.filterSpec(sbReg,true);
			sbCollect=this.collect(preStore,sbSpec,selectedHS,keys,true);
		}else{              
			sbCollect=this.filterSpec(new RegExp(""+hsvalue.join("|")+""),true);                   
		}                   
			
		if(hskey.length==this.specNum)return sbCollect;                
		var tpCollect=this.filterSpec(tpReg,true);   
		return this.collect(sbCollect,tpCollect,selectedHS,keys);
	},
	init:function(obj,specvid,specv_Arr){          
		selectedHS=this.selectedHS=this.sortKeys(obj.selectedHS);
		var specItems;	
		this.PRODUCT_HASH=obj.productData;
		this.specNum=obj.specItems.length;
		if(selectedHS.getKeys().length>1){              
			specItems=this.to_find(selectedHS,specvid).flatten();    
		}else{
			var regExp = new RegExp(":"+specvid+":");
			specItems=this.filterSpec(regExp).flatten();

			specv_Arr.each(function(item){
				if(item.contains(specvid))specItems.combine(item);	
			});
		}
		return specItems; 
	}
};  

var PRODUCT_HASH=new Hash(<{$goods.product2spec}>),SPEC_HASH=new Hash(<{$goods.spec2product}>);


var Goods_spec =this.Goods_spec=new Class({
		Implements:[Events,Options],
		options:{
			onLoad:$empty,
			onSelect:$empty,
			onComplete:$empty,
			onUpdate:$empty,
			productData:PRODUCT_HASH,
			spec_hash:SPEC_HASH,
			selectItems:[],
			lockCls:'lock',
			selectedCls:'selected',
			specBtn:'a[specvid]',
			specItems:'.spec-item'	
		},
		initialize:function(contains,options){
			if(!$(contains))return;	
			this.contains=$(contains);
			this.setOptions(options);	
			var option=this.options;
			this.productData=option.productData;
			this.spec_hash=option.spec_hash;
			this.specData=option.specData;
			this.specItems=this.contains.getElements(option.specItems);
			this.specBtn=this.contains.getElements(option.specBtn);
			this.fireEvent('load').bindEvent();
			Goods_spec._selectUpdate['updateBtn'](this.contains);
		},
		bindEvent:function(){
			 var self=this;
			 
			 this.specBtn.addEvent('click',function(e){
				 e.stop();
				 self.selectspec.call(self,this);	 
			 });			  
		},
		selectspec:function(specEl){
			 var options=this.options,lockCls=options.lockCls;

			 if(specEl.hasClass(options.lockCls))return;
			 var specid=specEl.get('specid'), specvid=specEl.get('specvid'),
				 selectedCls=options.selectedCls,contains=this.contains,
				 prt=specEl.getParent('ul');

			 if(specEl.hasClass(selectedCls)){
				specEl.removeClass(selectedCls); 
				var selected=this.selected=contains.getElements('.'+selectedCls),
					selectednum=selected.length;
				if(selectednum<=1){
					this.specSelectedCall(specvid,specid,specEl);
					this.specBtn.removeClass('lock');	
				}
				if(selectednum){
					specvid=selected[0].get('specvid');
					specid=selected[0].get('specid');			
				   this.specSelectedCall(specvid,specid,specEl);
				}
				return this;
			 }
			       
			 var tempsel=prt.retrieve('ts',specEl);
			 if(tempsel!=specEl){tempsel.removeClass(selectedCls);}
			 prt.store('ts',specEl.addClass(selectedCls));

			 this.selected=contains.getElements('.'+selectedCls);

			 this.specSelectedCall(specvid,specid,specEl);
		},
		specSelectedCall:function(specvid,specid,spec){
			var selectedHS=this.selectedHS=new Hash(),specItems=this.specItems,options=this.options,
				specEl=this.specEl,selectedCls=options.selectedCls,specBtn=options.specBtn,
				selected=this.selected,lockCls=options.lockCls,num=this.specItems.length,
				selectedBtn=this.selectedBtn=[];

		    specItems.each(function(item,i){
				var el;
				if(el=item.getElement('.'+selectedCls)){
					selectedBtn.push(el);
					selectedHS.set(i,el.get('specvid'));
				}
            });		

			var specArr=[],v;
			this.specItems.each(function(item,index){
				if(v=item.getElements(specBtn))specArr.push(v.get('specvid'));
			});

			var specAll=specExtend.init.call(specExtend,this,specvid,specArr);
			var pid=this.pid=specExtend.pid;

			this.specBtn.each(function(s){
				var bool=specAll.indexOf(s.get('specvid'))!=-1;
				s[bool?'removeClass':'addClass'](lockCls);
			});
			
			this.fireEvent('selected',spec).selectedcall(spec);
			if(!selectedBtn.length)return this.fireEvent('updatedefault').updatedefault();

			if(num==this.selected.length){
				this.update(pid,this.productData);
				this.complete(pid,this.productData);
			}
	    },
		selectedcall:function(target){
			var selectUpdate=this.options.selectItems.combine(['selectedItem','updateBtn','updatePic']);
			selectUpdate.each(function(n){
				var fn;
				if(fn=Goods_spec._selectUpdate[n]) fn.call(this,target);
			},this);
		},
		update:function(pid,pdata){
	  		var specUpdate=this.specUpdate=this.contains.getElements('[updateSpec]');
			if(!!specUpdate.length)
			specUpdate.each(function(el){
				var _k=el.get('updateSpec').split('_'),up,_v=pdata[pid][_k[1]];
				if(up=Goods_spec._selectedUpdate[_k[0]]) up(el,_v,pid,pdata);
			});
	    },
		updatedefault:function(){
			var specUpdate=this.contains.getElements('[updateSpec]'),value;
			specUpdate.each(function(el){
				if(value=el.retrieve('default:html',false))el.set(el.tagName=='INPUT'?'value':'html',value);
				if(value=el.retrieve('default:callback',false))value();
			});
	    },
		complete:function(){
			this.fireEvent('complete');   
		}		
 });


Goods_spec._selectUpdate={
	'selectedItem':function(spec){
		var em=(spec.getParent('.spec-item')).getElement('em');
		em[spec.hasClass('selected')?'addClass':'removeClass']('check');
	},
	'updateBtn':function(contains){
		contains=contains||this.contains;
        var updateBtn=contains.getElements('.updateBtn').store('tip:text','');
        if(!updateBtn)return;
		var spec_item_check=[],spec_item_selected=[];
        var check=function(){
            var spec_item_nocheck=[];
            $ES('.spec-item em',contains).each(function(em,i){
                if(!em.hasClass('check'))return spec_item_nocheck.include(em.getText());
				spec_item_check.include(em.getText());	
				spec_item_selected.include($ES('.spec-item .selected',contains)[i]);
            });
            return  spec_item_nocheck;
        }

        updateBtn.removeEvents('click').addEvent('click',function(e){
            e.stop(); this.blur();
            var spec_item_nocheck=check(),_form=this.getParent('form'),error=$E('.error',this.getParent());
            if(!spec_item_nocheck.length){
				if(!!error)error.destroy();
				if(!_form) return this.fireEvent('_update_spec',[spec_item_check,spec_item_selected]);
				if(_form.retrieve('events')&&_form.retrieve('events')['submit'])return _form.fireEvent('submit',[e,updateBtn]);
				return _form.submit();
			}			
			if(!error)error = new Element('span',{'class':'error'}).inject(this,'before'); 
			error.set('html','请选择规格:'+spec_item_nocheck.join(','));
        });
	},
	'updatePic':function(spec){
		var picsId=[],spec2image=$H(<{$goods.spec2image}>);
		this.selectedBtn.each(function(s){
			 picsId.combine(this.spec_hash[s.get('specvid')]['images']);
		},this);		
		if(picsId[0]&&spec2image[picsId[0]])$E('.spec_pic img',this.contains).src=spec2image[picsId[0]];
	}
};


var priceControl={
	 format:function(num){
		var part;
		if(!num)return;
		var num = num.toFloat();
			num = num.round(2)+'';
			var p =num.indexOf('.');
			if(p<0){
				p = num.length;
				part = '';
			}else{
				part = num.substr(p+1);
			}
			while(part.length<2){part+='0';}
			var c=[];
			while(p>0){
				if(p>2){
					c.unshift(num.substr(p-=3,3));
				}else{
					c.unshift(num.substr(0,p));
					break;
				}
			}
			if(!part){
				this._format.dec_point='';
			}
			return ("¥")+c.join("")+'.'+part;
	}
};


Goods_spec._selectedUpdate={
	'text':function(el,v){
		if(el.tagName=='INPUT')	return el.store('default:html',el.get('value')).set('value',v);
		return el.store('default:html',el.get('html')).set('html',v);	
	},
	'updateprice':function(el,v,pid,pdata){
		el.store('default:html',el.get('value')).set('html',priceControl.format(pdata[pid]['price']));
	},
	'updatepid':function(el,v,pid){
		el.store('default:html',el.get('value')).set('value',pid);
	}
};

})();      


</script>
